
const dbOps = require('@/utils/mysql.operate.js');
const {filterObjectByKeys } = require('@/utils/index.js');
const { get } = require('http');
// exports.findUser = async function (phoneNum) {
//     const result = await dbOps.getOne('user', { phone: phoneNum });
//     return result;
// }
function buildConditions(payload) {
    const conditions = {};
  
    for (const key in payload) {
      if (payload[key] !== undefined) {
        if (key.endsWith('_like')) {
          conditions[key.replace('_like', '')] = `%${payload[key]}%`;
        } else {
          conditions[key] = payload[key];
        }
      }
    }
  
    return conditions;
  }
async function getDeptList(payload) {
    const orderBy = 'order_num';
    const sortOrder = 'ASC';
    if(payload.dept_name){
        payload.dept_name_like = payload.dept_name;
    }
    const conditions = buildConditions(payload);
    const result = await dbOps.getAllByLike('sys_dept',conditions,orderBy,sortOrder)
    return result
}

async function addDept(payload) {
    const map = payload[0];
    const result = await dbOps.add('sys_dept',map)
    return result;
}

async function getDept(dept_id) {
    const result = await dbOps.getOne('sys_dept',{dept_id})
    return result;
}

async function deptListExclude() {
    const result = await dbOps.getAll('sys_dept',{status:0})
    return result;
}

async function updateDept(payload) {
    const { dept_id } = payload;
    const result = await dbOps.update('sys_dept', payload, {dept_id})
    return result;
}

async function delDept(dept_id) {
    const result = await dbOps.remove('sys_dept', {dept_id})
    return result;
}



async function getPostList(payload) {
    if(payload.post_name){
        payload.post_name_like = payload.post_name;
    }
    const allowedFields = ['post_code', 'post_name_like', 'status','post_sort'];
    const filterePayload = filterObjectByKeys(payload, allowedFields);

    const data = filterePayload
    const conditions = buildConditions(data);

     // 使用 Promise.all 确保两个异步操作同时完成
     const [postList, totalCount] = await Promise.all([
        await dbOps.getAllByLimit('sys_post', conditions,'post_sort','ASC', payload.pageNum, payload.pageSize ),
        dbOps.getTotal('sys_post')
    ]);
    return {rows:postList,total:totalCount};
}


async function addPost(payload) {
    const result = await dbOps.add('sys_post',payload)
    return result;
}


async function getPost(post_id) {
    const result = await dbOps.getOne('sys_post',{post_id})
    return result;
}



async function updatePost(payload) {
    const { post_id } = payload;
    const result = await dbOps.update('sys_post', payload, {post_id})
    return result;
}

async function delPost(post_id) {
    const result = await dbOps.remove('sys_post', {post_id})
    return result;
}



async function getMenuList(payload) {
    if(payload.menu_name){
        payload.menu_name_like = payload.menu_name;
    }
    const allowedFields = ['menu_id', 'menu_name', 'status', 'order_num'];
    const filterePayload = filterObjectByKeys(payload, allowedFields);

    const data = filterePayload;
    const conditions = buildConditions(data);

    const result = await dbOps.getAllByLimit('sys_menu', conditions,'order_num','ASC')
    return result
}


async function addMenu(payload) {
    const result = await dbOps.add('sys_menu',payload)
    return result;
}


async function getMenu(menu_id) {
    const result = await dbOps.getOne('sys_menu',{menu_id})
    return result;
}

async function updateMenu(payload) {
    const { menu_id } = payload;
    const result = await dbOps.update('sys_menu', payload, {menu_id})
    return result;
}

async function delMenu(menu_id) {
    const result = await dbOps.remove('sys_menu', {menu_id})
    return result;
}



async function getRoleList(payload) {
    // 如果提供了角色名称，则添加模糊查询条件
    if(payload.role_name){
        payload.role_name_like = payload.role_name;
    }
    // 允许的查询字段
    const allowedFields = ['role_id', 'role_name', 'role_key', 'status', 'role_sort'];
    
    // 过滤 payload 中的字段，只保留允许的字段
    const filterePayload = filterObjectByKeys(payload, allowedFields);

    // 构建查询条件
    const conditions = buildConditions(filterePayload);
    
    // 使用 Promise.all 确保两个异步操作同时完成
    const [roleList, totalCount] = await Promise.all([
        // 查询角色列表
        dbOps.getAllByLimit('sys_role', conditions, 'role_sort', 'ASC', payload.pageNum, payload.pageSize),
        // 查询总记录数
        dbOps.getTotal('sys_role', { del_flag: 0 })
    ]);
    return {rows:roleList,total:totalCount};
}


async function addRole(payload) {
    const result = await dbOps.add('sys_role',payload);
    return result;
}


async function getRole(role_id) {
    const result = await dbOps.getOne('sys_role',{role_id})
    return result;
}



async function updateRole(payload) {
    const { role_id } = payload;
    const allowedFields = ['role_id', 'role_name', 'role_key', 'status', 'role_sort','remark','data_scope'];
    const filterePayload = filterObjectByKeys(payload, allowedFields);

    const data = filterePayload;
    const conditions = buildConditions(data);
    console.log("conditions",conditions)
    const result = await dbOps.update('sys_role', conditions, {role_id})
    return result;
}

async function delRole(role_id) {
    const result = await dbOps.remove('sys_role', {role_id})
    return result;
}


async function getRoleMenu(payload) {
    const result = await dbOps.getAll('sys_role_menu',payload)
    return result;
}


async function getRoleDept(payload) {
    const result = await dbOps.getAll('sys_role_dept',payload)
    return result;
}

async function addRoleMenu(payload) {
    const result = await dbOps.addMuti('sys_role_menu',payload)
    return result;
}

async function deleteRoleMenu(payload) {
    let { role_id , menu_ids } = payload;
    menu_ids = menu_ids.join(',');
    const result = await dbOps.deleteRoleMuti('sys_role_menu', role_id,'menu_id', menu_ids);
    return result;
}


async function addRoleDept(payload) {
    const result = await dbOps.addMuti('sys_role_dept',payload)
    return result;
}

async function deleteRoleDept(payload) {
    let { role_id , dept_ids } = payload;
    dept_ids = dept_ids.join(',');
    const result = await dbOps.deleteRoleMuti('sys_role_dept', role_id,'dept_id', dept_ids);
    return result;
}


async function getUserList(payload) {
    if(payload.post_name){
        payload.post_name_like = payload.post_name;
    }
    const allowedFields = ['post_code', 'post_name_like', 'status', 'post_sort'];
    const filterePayload = filterObjectByKeys(payload, allowedFields);

    const data = filterePayload
    const conditions = buildConditions(data);

     // 使用 Promise.all 确保两个异步操作同时完成
     const [postList, totalCount] = await Promise.all([
        await dbOps.getAllByLimit('sys_user', conditions,'post_sort','ASC', payload.pageNum, payload.pageSize ),
        dbOps.getTotal('sys_user')
    ]);
    return {rows:postList,total:totalCount};
}

async function getUserListAll(payload) {
    if(payload.post_name){
        payload.post_name_like = payload.post_name;
    }
    const allowedFields = ['post_code', 'post_name_like', 'status', 'post_sort'];
    const filterePayload = filterObjectByKeys(payload, allowedFields);

    const data = filterePayload
    const conditions = buildConditions(data);

     // 使用 Promise.all 确保两个异步操作同时完成
     const [postList, totalCount] = await Promise.all([
        await dbOps.getAllByLimit('sys_user', conditions, payload.pageNum, payload.pageSize ),
        dbOps.getTotal('sys_user')
    ]);
    return {rows:postList,total:totalCount};
}


async function addUser(payload) {
    const result = await dbOps.add('sys_user',payload)
    return result;
}


async function getUser(post_id) {
    const result = await dbOps.getOne('sys_user',{post_id})
    return result;
}



async function updateUser(payload) {
    const { post_id } = payload;
    const result = await dbOps.update('sys_user', payload, {post_id})
    return result;
}

async function delUser(post_id) {
    const result = await dbOps.remove('sys_user', {post_id})
    return result;
}





async function getDictTypeList(payload) {
    
    const allowedFields = ['dict_name', 'dict_type', 'status'];
    const filterePayload = filterObjectByKeys(payload, allowedFields);

    const conditions = buildConditions(filterePayload);

     // 使用 Promise.all 确保两个异步操作同时完成
     const [list, totalCount] = await Promise.all([
        await dbOps.getAllByLimit('sys_dict_type', conditions,'','ASC', payload.pageNum, payload.pageSize ),
        dbOps.getTotal('sys_dict_type')
    ]);
    return {rows:list,total:totalCount};
}


async function addDictType(payload) {
    const result = await dbOps.add('sys_dict_type',payload)
    return result;
}


async function getDictType(dict_id) {
    const result = await dbOps.getOne('sys_dict_type',{dict_id})
    return result;
}


async function updateDictType(payload) {
    const { dict_id } = payload;
    const result = await dbOps.update('sys_dict_type', payload, {dict_id})
    return result;
}

async function delDictType(dict_id) {
    const result = await dbOps.remove('sys_dict_type', {dict_id})
    return result;
}


async function getDictDataList(payload) {
    
    const allowedFields = ['dict_name', 'dict_type', 'status'];
    const filterePayload = filterObjectByKeys(payload, allowedFields);

    const conditions = buildConditions(filterePayload);

     const [list, totalCount] = await Promise.all([
        dbOps.getAllByLimit('sys_dict_data', conditions,'dict_sort','ASC', payload.pageNum, payload.pageSize ),
        dbOps.getTotal('sys_dict_data',{dict_type:payload.dict_type})
    ]);
    return {rows:list,total:totalCount};
}


async function dictDataTypeQuery(dict_type) {
    let res = await dbOps.getAll('sys_dict_data',{dict_type:dict_type});
    return res
}


async function addDictData(payload) {
    const result = await dbOps.add('sys_dict_data',payload)
    return result;
}


async function getDictData(dict_code) {
    const result = await dbOps.getOne('sys_dict_data',{dict_code})
    return result;
}


async function updateDictData(payload) {
    const { dict_code } = payload;
    const result = await dbOps.update('sys_dict_data', payload, {dict_code})
    return result;
}

async function delDictData(dict_code) {
    const result = await dbOps.remove('sys_dict_data', {dict_code})
    return result;
}




async function getDictDataList(payload) {
    
    const allowedFields = ['dict_name', 'dict_type', 'status'];
    const filterePayload = filterObjectByKeys(payload, allowedFields);

    const conditions = buildConditions(filterePayload);

     const [list, totalCount] = await Promise.all([
        dbOps.getAllByLimit('sys_dict_data', conditions,'dict_sort','ASC', payload.pageNum, payload.pageSize ),
        dbOps.getTotal('sys_dict_data',{dict_type:payload.dict_type})
    ]);
    return {rows:list,total:totalCount};
}


async function addDictData(payload) {
    const result = await dbOps.add('sys_dict_data',payload)
    return result;
}


async function getDictData(dict_code) {
    const result = await dbOps.getOne('sys_dict_data',{dict_code})
    return result;
}


async function updateDictData(payload) {
    const { dict_code } = payload;
    const result = await dbOps.update('sys_dict_data', payload, {dict_code})
    return result;
}

async function delDictData(dict_code) {
    const result = await dbOps.remove('sys_dict_data', {dict_code})
    return result;
}


async function getconfigList(payload) {
    
    const allowedFields = ['config_key', 'config_name'];
    const filterePayload = filterObjectByKeys(payload, allowedFields);

    const conditions = buildConditions(filterePayload);

     const [list, totalCount] = await Promise.all([
        dbOps.getAllByLimit('sys_config', conditions,'','ASC', payload.pageNum, payload.pageSize ),
        dbOps.getTotal('sys_config')
    ]);
    return {rows:list,total:totalCount};
}


async function addConfig(payload) {
    const result = await dbOps.add('sys_config',payload)
    return result;
}


async function getConfig(config_id) {
    const result = await dbOps.getOne('sys_config',{config_id})
    return result;
}


async function updateConfig(payload) {
    const { config_id } = payload;
    const result = await dbOps.update('sys_config', payload, {config_id})
    return result;
}

async function delConfig(config_id) {
    const result = await dbOps.remove('sys_config', {config_id})
    return result;
}

async function getNoticeList(payload) {
    
    const allowedFields = ['notice_content','notice_title','notice_type'];
    const filterePayload = filterObjectByKeys(payload, allowedFields);

    const conditions = buildConditions(filterePayload);

     const [list, totalCount] = await Promise.all([
        dbOps.getAllByLimit('sys_notice', conditions,'','ASC', payload.pageNum, payload.pageSize ),
        dbOps.getTotal('sys_notice')
    ]);
    return {rows:list,total:totalCount};
}


module.exports = { 
    getDeptList,
    addDept,
    getDept,
    deptListExclude,
    updateDept,
    delDept,

    getPostList,
    addPost,
    getPost,
    updatePost,
    delPost,

    getMenuList,
    addMenu,
    getMenu,
    updateMenu,
    delMenu,

    getRoleList,
    addRole,
    getRole,
    updateRole,
    delRole,
    addRoleMenu,
    deleteRoleMenu,
    addRoleDept,
    deleteRoleDept,
    getRoleMenu,
    getRoleDept,
    getUserListAll,


    getUserList,
    addUser,
    getUser,
    updateUser,
    delUser,


    getDictTypeList,
    addDictType,
    getDictType,
    updateDictType,
    delDictType,


    getDictDataList,
    dictDataTypeQuery,
    addDictData,
    getDictData,
    updateDictData,
    delDictData,


    getconfigList,
    addConfig,
    getConfig,
    updateConfig,
    delConfig,



    getNoticeList



};




